package co.fitstart.weapp.api.handler.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.demo2do.core.entity.result.Result;

import co.fitstart.entity.utils.JsonUtils;
import co.fitstart.weapp.api.handler.TencentHandler;

/**
 * 
 * @author haiyan_xiao
 *
 */
@Component("tencentHandler")
public class TencentHandlerImpl implements TencentHandler {

    private static final Logger logger = LoggerFactory.getLogger(TencentHandler.class);

    @Value("#{ctx['api.host']}")
    private String APIHOST;

    @Value("#{config['sms.mock']}")
    private boolean mock;

    /*
     * (non-Javadoc)
     * @see co.fitstart.weapp.api.handler.TencentHandler#sendCorpMessage(java.lang.String, java.lang.String)
     */
    public Result sendCorpMessage(String message, String mobile) {
        Result result = new Result();
        
        try {
            if(mock) {
                result.success().message("发送成功");
            } else {
                Map<String, String> parameters = new HashMap<>();
                parameters.put("message", message);
                parameters.put("mobile", mobile);
                
                String content = JsonUtils.toJsonString(parameters);
                
                Response response = Request.Post(APIHOST + "/v1/send-corp-message")
                                           .bodyString(content, ContentType.APPLICATION_JSON)
                                           .connectTimeout(100000)
                                           .socketTimeout(100000)
                                           .execute();
                
                String body = response.returnContent().asString(Consts.UTF_8);
                
                logger.trace("TencentHandler#sendCorpMessage() - Get response body [{}].", body);
                
                result = JSON.parseObject(body, Result.class);
            }
        } catch (Exception e) {
            logger.error("TencentHandler#sendCorpMessage() - Request wechat send corp message api euncouters exception: [{}]", e);
        }
        return result;
    }

}
